/*******************************************************************************
 * Package: com.hngtrust.iir.user.controller
 * Type:    GenerateReportController
 * Date:    2021/6/2 9:54
 *
 * Copyright (c) 2021 HUANENG GUICHENG TRUST CORP.,LTD All Rights Reserved.
 *
 * You may not use this file except in compliance with the License.
 *******************************************************************************/
package com.hngtrust.iir.user.controller;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.hngtrust.framework.bind.ResponseInfo;
import com.hngtrust.framework.id.service.MyIdGenerator;
import com.hngtrust.framework.page.PageResult;
import com.hngtrust.framework.page.service.PageService;
import com.hngtrust.framework.security.util.SecurityUtils;
import com.hngtrust.iir.base.controller.vo.OptLogReqVO;
import com.hngtrust.iir.base.service.LogService;
import com.hngtrust.iir.constant.Constant;
import com.hngtrust.iir.dto.ReqDTO;
import com.hngtrust.iir.myreport.dto.ListMyReportRespVO;
import com.hngtrust.iir.myreport.dto.MyReportReqVO;
import com.hngtrust.iir.myreport.entity.SelfReport;
import com.hngtrust.iir.myreport.service.SelfReportService;
import com.hngtrust.iir.user.controller.dto.ListGenerateReportReqVO;
import com.hngtrust.iir.user.controller.dto.ListGenerateReportRespVO;
import com.hngtrust.iir.user.controller.dto.ListViewBuildReportReqVO;
import com.hngtrust.iir.user.controller.dto.MyReportVO;
import com.hngtrust.iir.user.controller.dto.QueryMyReportVO;
import com.hngtrust.iir.user.entity.User;
import com.hngtrust.iir.user.service.GenerateReportService;
import com.hngtrust.iir.util.DateUtils;
import com.tiger.web.annotation.DownloadMapping;
import com.tiger.web.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.util.Date;

/**
 * 生成报告
 *
 * @author Wanghan
 * @date 2021/6/2 9:54
 */

@Api(tags = "我的报告")
@Slf4j
@RestController
@RequestMapping("/my-report")
public class GenerateReportController {
    
    //ID生成
    @Autowired
    private MyIdGenerator myIdGenerator;
    
    //内部研报表
    @Autowired
    private SelfReportService selfReportService;
    
    @Autowired
    private PageService pageService;
    
    @Autowired
    private LogService logService;
    
    @Autowired
    private GenerateReportService generateReportService;
    
    @Autowired
    private FileService fileService;
    
    @Value("${word.template}")
    private String wordTemplate;
    
    private static final String DIRECTORY = System.getProperty("java.io.tmpdir");
    
    /**
     * 生成报告
     */
    @ApiOperation(value = "生成报告", notes = "生成报告")
    @PostMapping("/add-generatereport")
    public ResponseInfo<Long> addGenerateReport(@ApiParam(value = "生成报告") @Valid @RequestBody ListGenerateReportReqVO req) {
        SelfReport selfReport = new SelfReport();
        selfReport.setId(myIdGenerator.nextId());//Id
        selfReport.setStatus(Constant.DEFAULT_STATUS_NORMAL);//状态
        BeanUtils.copyProperties(req,selfReport);
        selfReport.setCreateTime(new Date());//创建时间
        selfReport.setUpdateTime(new Date());//修改时间
        User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
        selfReport.setCreateUserId(loginUser.getId());//创建人
        selfReport.setUpdateUserId(loginUser.getId());//修改人
        selfReportService.add(selfReport);
        return new ResponseInfo<>(selfReport.getId());
    }
    
    /**
     * 查看我的报告
     */
    @ApiOperation(value = "查看我的报告", notes = "查看我的报告")
    @PostMapping("/list-generatereport")
    public ResponseInfo<ListGenerateReportRespVO> listGenerateReport(@ApiParam(value = "查看我的报告") @Valid @RequestBody ListViewBuildReportReqVO req){
        SelfReport selfReport = selfReportService.queryById(req.getId());
        ListGenerateReportRespVO resp = new ListGenerateReportRespVO();
        BeanUtils.copyProperties(selfReport,resp);
        ResponseInfo<ListGenerateReportRespVO> data = new ResponseInfo<>();
        data.setData(resp);
        return data;
    }
    
    @ApiOperation("删除研报")
    @PostMapping("/delete-report")
    public ResponseInfo<Object> deleteReport(@ApiParam("研报参数") @Valid @RequestBody MyReportVO vo){
        SelfReport selfReport = selfReportService.queryById(vo.getId());
        selfReportService.deleteById(vo.getId());
        OptLogReqVO vo1 =new OptLogReqVO();
        vo1.setStatus(1);
        vo1.setOptType(8);
        vo1.setOptModule(10);
        vo1.setOptContent("删除"+selfReport.getReportName());
        logService.saveOptLog(vo1);
        return new ResponseInfo<Object>();
    }
    
    @ApiOperation("我的研报列表")
    @PostMapping("/list-report")
    public ResponseInfo<PageResult<ListMyReportRespVO>> listReport(@ApiParam("分页参数") @Valid @RequestBody ReqDTO<QueryMyReportVO> dto){
        //开始日期
        String beginTime = null;
        //结束日期
        String endTime = null;
        
        if (Constant.COMP_RISK_TIME_DAY.equals(dto.getContent().getType())) {
            beginTime = DateUtil.format(DateUtil.offsetDay(DateUtil.date(), -29), DatePattern.NORM_DATE_PATTERN);
            endTime = DateUtil.format(DateUtil.offsetDay(DateUtil.date(), 0), DatePattern.NORM_DATE_PATTERN)
                    + " 23:59:59";
        } else if (Constant.COMP_RISK_TIME_WEEK.equals(dto.getContent().getType())) {
            beginTime = DateUtil.format(DateUtil.offsetDay(DateUtil.date(), -7), DatePattern.NORM_DATE_PATTERN);
            endTime = DateUtil.format(DateUtil.offsetDay(DateUtil.date(), 0), DatePattern.NORM_DATE_PATTERN)+" 23:59:59";
        } else if (Constant.COMP_RISK_TIME_MONTH.equals(dto.getContent().getType())) {
            beginTime = DateUtil.format(DateUtil.offsetDay(DateUtil.date(), -3), DatePattern.NORM_DATE_PATTERN);
            endTime = DateUtil.format(DateUtil.offsetDay(DateUtil.date(), 0), DatePattern.NORM_DATE_PATTERN)+" 23:59:59";
        }
    
        MyReportReqVO vo = new MyReportReqVO();
        User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
        vo.setCompName(dto.getContent().getCompName());
        vo.setStartTime(beginTime);
        vo.setEndTime(endTime);
        vo.setCreateId(loginUser.getId());
        PageResult<ListMyReportRespVO> page = pageService.page(dto.getPageParam(),()->selfReportService.queryListReport(vo));
        return new ResponseInfo<>(page);
    }
    
    @ApiOperation("下载研报")
    @DownloadMapping("/upload-report")
    public void uploadReport(@ApiParam("参数")  ListViewBuildReportReqVO vo,HttpServletResponse response) {
        
        SelfReport selfReport = selfReportService.queryById(vo.getId());
        OptLogReqVO vo1 =new OptLogReqVO();
        vo1.setStatus(1);
        vo1.setOptType(12);
        vo1.setOptModule(10);
        vo1.setOptContent("下载"+selfReport.getReportName());
        logService.saveOptLog(vo1);
        try {
            String upload;
            if (selfReport.getPath() != null && !selfReport.getPath().isEmpty()){
                upload=selfReport.getPath();
            }else {
                String url = wordTemplate + Constant.PATH;
                String path = DIRECTORY+DateUtils.toString(new Date(),"yyyyMMddHHmmss")+".docx";
                File file = new File(path);
                fileService.download(url,file);
                upload = generateReportService.upload(selfReport, path);
            }
            fileService.download(upload,response);
        }catch (Exception e){
            e.printStackTrace();
        }
       
    }
    
}
